<html>
<head>

<title>Groovy Goodness: Navigating with GPath</title>

<script language="javascript" src="scripts/shCore.js"></script> 
<script language="javascript" src="scripts/shLegacy.js"></script> 
<script language="javascript" src="scripts/shBrushJava.js"></script> 
<script language="javascript" src="scripts/shBrushXml.js"></script> 
<script language="javascript" src="scripts/shBrushJScript.js"></script> 
<script language="javascript" src="scripts/shBrushGroovy.js"></script> 
<script language="javascript" src="scripts/shBrushPlain.js"></script> 
<script language="javascript" src="scripts/shBrushBash.js"></script> 
 
<link href="styles/reset.css" rel="stylesheet" type="text/css" />
<link href="styles/shCore.css" rel="stylesheet" type="text/css" />
<link type="text/css" rel="stylesheet" href="styles/shThemeRDark.css"/>
<link href="styles/blog.css" rel="stylesheet" type="text/css" />

</head>
<body>

<a href="index.html">Back to index</a>

<h3 class="post-title">Groovy Goodness: Navigating with GPath</h3>

<div class="post">
<p>Groovy has GPath, a path expression language to navigate in XML or POJOs. We can use a simple dot-notation to identify elements in XML or a set of POJOs. This results in clean and dense code.</p>
<pre class="brush:groovy">
def xml = '''
&lt;languages&gt;
    &lt;language id=&quot;1&quot; jvm=&quot;true&quot;&gt;Groovy&lt;/language&gt;
    &lt;language id=&quot;2&quot; jvm=&quot;true&quot;&gt;Java&lt;/language&gt;
    &lt;language id=&quot;3&quot; jvm=&quot;false&quot;&gt;Ruby&lt;/language&gt;
&lt;/languages&gt;
'''

def languages = new XmlSlurper().parseText(xml)
// Navigate in XML with GPath.
assert 3 == languages.language.size()
assert 'Groovy' == languages.language.find { it.'@id' = 1 }.text()
assert ['Groovy', 'Java', 'Ruby'] == languages.language.collect { it.text() }
assert 1 == languages.language.find { it = /Groovy/ }['@id'].toInteger()

// Navigating with GPath through object graph.
assert 75 == String.metaClass.methods.name.size()
assert ['copyValueOf', 'format', 'valueOf'] == String.metaClass.methods.findAll { it.static }.name.unique()
assert ['replace', 'replace', 'replaceAll', 'replaceFirst'] == String.metaClass.methods.name.grep(~/replace.*/)
assert ['class', 'bytes', 'empty'] == String.metaClass.properties.name
assert ['java.lang.Class', 'byte[]', 'boolean'] == String.metaClass.properties.type.canonicalName
</pre>
</div>

<script language="javascript"> 
SyntaxHighlighter.config.bloggerMode = true;
SyntaxHighlighter.config.clipboardSwf = 'scripts/clipboard.swf';
SyntaxHighlighter.defaults['first-line'] = 0;
SyntaxHighlighter.defaults['auto-links'] = false;
SyntaxHighlighter.all();
dp.SyntaxHighlighter.HighlightAll('code');
</script>

</body>
</html>